package com.example.com.baruffini_mele.booking4u;



import java.util.Calendar;
import java.util.Date;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

public class BookingFormActivity extends Activity {
	private static final String TAG = "BookingFormActivity";	
	
	
	String calendarId;
	String calendarName;
	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        
        Intent intent = getIntent(); // gets the previously created intent
        calendarId = intent.getStringExtra("calendarId");
        calendarName = intent.getStringExtra("calendarName");
        
        setContentView(R.layout.activity_booking_form_layout);
        
        TextView title = (TextView)findViewById(R.id.textView_room_name);
        title.setTextColor(getResources().getColor(R.color.blue));
        title.setTextSize(getResources().getDimension(R.dimen.title_3));
        title.setText(calendarName);
        
        Button submitBooking  = (Button)findViewById(R.id.button_submit_booking);
        
        
		
        submitBooking.setOnClickListener(new View.OnClickListener()  {
        	
            public void onClick(View v)
            {

            	
            	DatePicker dp = (DatePicker) findViewById(R.id.dayPicker);	
            	
        		TimePicker tps = (TimePicker) findViewById(R.id.timeStartPicker);
        		tps.setIs24HourView(true);
        		
        		TimePicker tpe = (TimePicker) findViewById(R.id.timeEndPicker);
        		tpe.setIs24HourView(true);
        		
        		EditText eventDescription = (EditText) findViewById(R.id.editText_description);
        		int difHour = tpe.getCurrentHour() - tps.getCurrentHour();
        		int difMin = tpe.getCurrentMinute() - tps.getCurrentMinute();
                Date fromPicker = new Date(dp.getYear() - 1900, dp.getMonth(), dp.getDayOfMonth());
        		Date now = new Date();
                //GEvent myGE = new GEvent();
        		
            	
		/*check event date after current date*/

            	/* ******************************** */
          	if (fromPicker.before(getZeroTimeDate(now))) {
            				
    				 AlertDialog.Builder wrongDateBuilder = new AlertDialog.Builder(BookingFormActivity.this);
        			// set title
    				 wrongDateBuilder.setTitle(R.string.wrong_date_title);
            		// set dialog message
    				 wrongDateBuilder.setMessage(R.string.wrong_date_text);
            		// set positive button
    				 wrongDateBuilder.setPositiveButton(R.string.wrong_date_button, new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int id) {
						// TODO Auto-generated method stub
						
						// if this button is clicked, close
						// the dialog box and start next activity
						 dialog.cancel();
					}
        					
        					
        					
      				});
            				// create alert dialog
                           	AlertDialog alertWrongDate = wrongDateBuilder.create();
                           	// show it
                           	alertWrongDate.show();		
            				
            	   }  	
                    	
            			
                /*check starting time before ending time*/
           	    /* ******************************** */
            	else if((difHour * 60 + difMin) <= 0){
                            	
                            	AlertDialog.Builder wrongTimeBuilder = new AlertDialog.Builder(BookingFormActivity.this);
                    			// set title
                            	wrongTimeBuilder.setTitle(R.string.wrong_time_title);
                        		// set dialog message
                            	wrongTimeBuilder.setMessage(R.string.wrong_time_text);
                        		// set positive button
                            	
                            	
                            	wrongTimeBuilder.setPositiveButton(R.string.wrong_time_button, new DialogInterface.OnClickListener() {
            					
            					@Override
            					public void onClick(DialogInterface dialog, int id) {
            						// TODO Auto-generated method stub
            						
            						// if this button is clicked, close
            						// the dialog box and start next activity
            						 dialog.cancel();
            					}
         				});
                        	
                				// create alert dialog
                             	AlertDialog alertWrongTime = wrongTimeBuilder.create();
                             	// show it
                             	alertWrongTime.show();
                            	
            	}
                        
                         /*check event description not null*/
                 	      /* ******************************** */
                         
            	else if (eventDescription.getText().length()==0){
                    		 AlertDialog.Builder missingDescriptionBuilder = new AlertDialog.Builder(BookingFormActivity.this);
                 			// set title
                    		 missingDescriptionBuilder.setTitle(R.string.missing_description_title);
                     		// set dialog message
                    		 missingDescriptionBuilder.setMessage(R.string.missing_description_text);
                     		// set positive button
                    		 missingDescriptionBuilder.setPositiveButton(R.string.missing_description_button, new DialogInterface.OnClickListener() {
         					
         					@Override
         					public void onClick(DialogInterface dialog, int id) {
         						// TODO Auto-generated method stub
         						
         						// if this button is clicked, close
         						// the dialog box and start next activity
         						 dialog.cancel();
   	
         					}
  				});
                     	
             				// create alert dialog
                          	AlertDialog alertMissingDescription = missingDescriptionBuilder.create();
                          	// show it
                          	alertMissingDescription.show();

        	}else{
            		//create event object and fill with correctly formatted parameters
            		GEvent event2insert = new GEvent();
            		event2insert.setEventDate(dp.getYear()+"-"+((dp.getMonth()+1) < 10 ? "0"+(dp.getMonth()+1) : (dp.getMonth()+1))+"-"+(dp.getDayOfMonth()<10 ? "0"+dp.getDayOfMonth() : dp.getDayOfMonth()));
            		event2insert.setStartTime((tps.getCurrentHour()<10 ?  "0"+tps.getCurrentHour() : tps.getCurrentHour()) +":"+(tps.getCurrentMinute() < 10 ? "0"+tps.getCurrentMinute() : tps.getCurrentMinute())+":00");
            		event2insert.setEndTime((tpe.getCurrentHour()<10 ?  "0"+tpe.getCurrentHour() : tpe.getCurrentHour()) +":"+(tpe.getCurrentMinute() < 10 ? "0"+tpe.getCurrentMinute() : tpe.getCurrentMinute())+":00");
            		event2insert.setTitle(eventDescription.getText().toString());
            		
            		event2insert.setIdCalendar(calendarId);
            		
            		Log.v(TAG, "day = "+dp.getYear()+"-"+((dp.getMonth()+1) < 10 ? "0"+(dp.getMonth()+1) : (dp.getMonth()+1))+"-"+(dp.getDayOfMonth()<10 ? "0"+dp.getDayOfMonth() : dp.getDayOfMonth()));
            		Log.v(TAG, "start = "+(tps.getCurrentHour()<10 ?  "0"+tps.getCurrentHour() : tps.getCurrentHour()) +":"+(tps.getCurrentMinute() < 10 ? "0"+tps.getCurrentMinute() : tps.getCurrentMinute())+":00");
            		Log.v(TAG, "end = "+(tpe.getCurrentHour()<10 ?  "0"+tpe.getCurrentHour() : tpe.getCurrentHour()) +":"+(tpe.getCurrentMinute() < 10 ? "0"+tpe.getCurrentMinute() : tpe.getCurrentMinute())+":00");
            		Log.v(TAG, "title = "+eventDescription.getText().toString());
                	
            		// execute post request
                    event2insert.postNewEvent();
                    Intent go2src = new Intent(getBaseContext(), ShowRoomCalendarActivity.class);
                    go2src.putExtra("calendarId",calendarId);
                    go2src.putExtra("calendarName",calendarName);
                	startActivity(go2src);
            	}  

                            
                            /*check events conflicts */
                   	        /* ******************************** */
                      	
                      	
                             /*end check events conflicts*/
                     	     /* ******************************** */ 
                    	
            			
                
            } 
        });
        
       
        
        
        
      
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_booking_form_menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) 
        {
        	// if help selected
            case R.id.bookingForm_menu_home:
            	// start Main
               startActivity(new Intent(this, MainActivity.class));
            return true;
            case R.id.bookingForm_menu_back:
            	//start Select Room
            	
            	Intent intent = new Intent(getBaseContext(), ShowRoomCalendarActivity.class);
            	intent.putExtra("calendarId",calendarId);
            	intent.putExtra("calendarName",calendarName);
            	startActivity(intent);
            return true;
            
           

            
        }// end switch on menu item
        return(super.onOptionsItemSelected(item));
    } 
    
    
    private static Date getZeroTimeDate(Date fecha) {
        Date res = fecha;
        Calendar calendar = Calendar.getInstance();

        calendar.setTime( fecha );
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        res = calendar.getTime();

        return res;
    }
    
    
}
